#!/usr/bin/env python
import cgi
import urllib
import urllib2
import httplib
from xml.dom import minidom

form = cgi.FieldStorage() 

if form.has_key('user'): name=form.getvalue('user')
if form.has_key('pass'): passwd=form.getvalue('pass')

#Chequeamos el registro. Necesitamos la BD.
parametros = urllib.urlencode({"_query":"//user[@name='"+name+"']","_wrap":"no"})
respuesta = urllib2.urlopen("http://localhost:8080/exist/rest/db/usuarios/?"+parametros)
respuesta = respuesta.read()

if respuesta=='':
	modificacion = """<xupdate:modifications version="1.0"  xmlns:xupdate="http://www.xmldb.org/xupdate">
	<xupdate:insert-before select="//user[1]" >  
		<xupdate:element name="user">
			<xupdate:attribute name="name">"""+name+"""</xupdate:attribute>
			<xupdate:attribute name="pass">"""+passwd+"""</xupdate:attribute>
		</xupdate:element>  
	</xupdate:insert-before> 
	</xupdate:modifications>""" 
	
	conn = httplib.HTTP("localhost:8080")
	conn.putrequest("POST", "/exist/rest/db/usuarios")
	conn.putheader('Content-Type', 'text/xml')
	clen = len(modificacion)
	conn.putheader('Content-Length', `clen`)
	conn.endheaders()
	conn.send(modificacion)
	response = conn.getreply()
	if response[0]!=200:
		print """\
		Content-Type: text/plain\n
		CreationFailed
		"""
	else:
		print """\
		Content-Type: text/plain\n
		CreationCompleted
		"""
	conn.close()
else:

	dom = minidom.parseString(respuesta)
	trad = dom.getElementsByTagName('user')

	usuario = {'name':trad[0].attributes['name'].nodeValue,'pass':trad[0].attributes['pass'].nodeValue}

	if usuario['pass']==passwd:
		print """\
		Content-Type: text/plain\n
		LoginOK
		"""
	else:
		print """\
		Content-Type: text/plain\n
		LoginFailure
		"""
	
